package org.moyakarta.server;

import java.io.IOException;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class MapsServlet extends GenericServlet
{

   /**
    * 
    */
   private static final long serialVersionUID = 4787246679951274988L;

   @Override
   public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException
   {
      HttpServletRequest httpRequest = (HttpServletRequest)req;
      
      String requestURI = httpRequest.getRequestURI();
      

      String redirectURI = httpRequest.getQueryString() == null ? requestURI.substring(5) : requestURI.substring(5) + "?" + httpRequest.getQueryString();
      
      if (requestURI.equalsIgnoreCase("/maps") 
            || requestURI.contains(".html") 
            || isMapRequest(requestURI)) 
         processMainPage(httpRequest, res);
      else if (requestURI.endsWith(".js") 
            || requestURI.endsWith(".jpg")
            || requestURI.endsWith(".css")) 
         httpRequest.getRequestDispatcher(redirectURI).forward(req, res);
      else 
         httpRequest.getRequestDispatcher(redirectURI).forward(req, res);
      
   }

   private boolean isMapRequest(String requestURI) {
      if (requestURI.indexOf("google-maps-mobile") > 0 
            || requestURI.indexOf("google-maps") > 0
            || requestURI.indexOf("yandex-maps") > 0
            || requestURI.indexOf("visicom-maps") > 0) 
         return true ;
      return false;
   }

   private void processMainPage(ServletRequest req, ServletResponse res) throws IOException, ServletException{
      res.setContentType("text/html; charset=utf-8");
      HttpServletRequest httpRequest = (HttpServletRequest)req;
      httpRequest.getRequestDispatcher("/jsp/main.jsp" + "?" + httpRequest.getQueryString()).include(req, res);
   }
   
   

}
